package git.soulbgm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import git.soulbgm.config.SysConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import git.soulbgm.pojo.NodeInfo;
import git.soulbgm.service.NodeInfoService;
import git.soulbgm.mapper.NodeInfoMapper;

import java.util.List;
import java.util.stream.Collectors;

import static git.soulbgm.common.MonitorConstants.*;

/**
 * 硬件设备信息表
 *
 * @author SoulBGM
 * @date 2020-11-18 10:03:05
 */
@Service("node")
public class NodeInfoServiceImpl extends ServiceImpl<NodeInfoMapper, NodeInfo> implements NodeInfoService {

    @Override
    public Integer getNodeCode() {
        List<Integer> codeList = list(new LambdaQueryWrapper<NodeInfo>().select(NodeInfo::getNodeCode)).stream().map(NodeInfo::getNodeCode).sorted().collect(Collectors.toList());
        int code = 1;
        if (!codeList.isEmpty()) {
            Integer dbMaxCode = codeList.get(codeList.size() - 1);
            code = dbMaxCode + 1;
        }
        return code;
    }

    @Override
    public Boolean checkUnique(NodeInfo info, Integer code) {
        LambdaQueryWrapper<NodeInfo> wrapper = new LambdaQueryWrapper<>();
        if (CHECK_UNIQUE_NODE_CODE == code) {
            wrapper.eq(NodeInfo::getNodeCode, info.getNodeCode());
        } else if (CHECK_UNIQUE_IP == code) {
            wrapper.eq(NodeInfo::getIp, info.getIp());
        }
        if (info.getId() != null) {
            wrapper.ne(NodeInfo::getId, info.getId());
        }
        List<NodeInfo> nodeInfos = list(wrapper);
        return nodeInfos.isEmpty();
    }

    /**
     * Cacheable
     * value：缓存key的前缀。
     * key：缓存key的后缀。
     * sync：设置如果缓存过期是不是只放一个请求去请求数据库，其他请求阻塞，默认是false。
     */
    @Cacheable(value = "nodeInfoAll", sync = true)
    @Override
    public List<NodeInfo> getCacheNodeInfoAll() {
        return list(new LambdaQueryWrapper<NodeInfo>().eq(NodeInfo::getRegionCode, SysConfig.getConfig().getRegionCode()));
    }

    @CacheEvict(value = {"nodeInfoAll", "nodeInfo"}, allEntries = true)
    @Override
    public void clearCache() {
    }

}